package com.usian.controller;

import com.usian.pojo.User;
import com.usian.service.UserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;


@Controller
@RequestMapping("user")
public class UserController {

    private static final Logger LOGGER= LoggerFactory.getLogger(UserController.class);

    @Autowired
    UserService userService;

    //查询所有
    @RequestMapping("findAll")
    public String findAll(Model model){
        List<User> userList = userService.findAll();
        model.addAttribute("userList",userList);
        LOGGER.debug("22222");
        System.out.println("666666");
        return "list";
    }

    @RequestMapping("findById/{id}")
    @ResponseBody
    public User findById(@PathVariable Integer id){
        return  userService.findById(id);
    }

//    @RequestMapping("findByUserName/{name}/{password}")
//    @ResponseBody
//    public List<User>findByUserName(@PathVariable String name,@PathVariable String password){
//        return userService.findByUserName(name,password);
//    }
    @RequestMapping("addUser")
    public String insertUser(User user){
        if (user!=null && user.getUserId()!=null){
            userService.updateUser(user);
        }else {
            userService.insertUser(user);
        }
         return "redirect:/user/findAll";
    }

    @RequestMapping("toDelete")
    public String toDelete(Integer userId){
        if (userId!=null){
            userService.delUser(userId);
            return "redirect:/user/findAll";
        }
        return "";
    }

    @RequestMapping("toUpdate")
    public String toUpdate(Integer userId,Model model){
        User user=userService.findById(userId);
        model.addAttribute("user",user);
        return "update";
    }


    @RequestMapping("toAdd")
    public String toAdd(){
        return "add";
    }

    @RequestMapping("login")
    public String login(Model model, User users, HttpSession session) {
        User user = userService.login(users);
        if(user!=null){
            session.setAttribute("user", user);
            return "redirect:/user/findAll";
        }
        return "login";
    }

}
